from flask import Flask, render_template, request, redirect, url_for, session, jsonify
import csv
import os
import uuid
from datetime import datetime

app = Flask(__name__)
app.secret_key = os.urandom(24)

# CSV文件配置
CSV_FILE = 'users.csv'
CSV_HEADERS = ['id', 'username', 'password', 'expiry_date']

# 初始化CSV文件
def init_csv():
    try:
        with open(CSV_FILE, 'x', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=CSV_HEADERS)
            writer.writeheader()
    except FileExistsError:
        pass

# 读取用户数据
def read_users():
    users = []
    with open(CSV_FILE, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            users.append(row)
    return users

# 写入用户数据
def save_users(users):
    with open(CSV_FILE, 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=CSV_HEADERS)
        writer.writeheader()
        writer.writerows(users)

# 新增登录验证装饰器
def login_required(f):
    def wrapper(*args, **kwargs):
        if not session.get('logged_in'):
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    wrapper.__name__ = f.__name__
    return wrapper

# 新增登录路由
@app.route('/api_login', methods=['POST'])
def api_login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('passwd')
    
    users = read_users()
    user = next((u for u in users if u['username'] == username and u['password'] == password), None)
    
    if not user:
        return jsonify({'status': 'pw_wrong'})
    
    expiry_date = datetime.strptime(user['expiry_date'], '%Y-%m-%d').date()
    if expiry_date < datetime.now().date():
        return jsonify({'status': 'dateout'})
    
    return jsonify({'status': 'pw_ok'})

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        with open('admin_users.csv', 'r') as f:
            reader = csv.DictReader(f)
            for row in reader:
                if row['username'] == username and row['password'] == password:
                    session['logged_in'] = True
                    return redirect(url_for('index'))
        return '无效的凭证'
    return render_template('login.html')

# 修改现有路由添加装饰器
@app.route('/')
@login_required
def index():
    users = read_users()
    # 检查账户是否过期
    current_date = datetime.now().date()
    for user in users:
        expiry = datetime.strptime(user['expiry_date'], '%Y-%m-%d').date()
        user['expired'] = expiry < current_date
    return render_template('index.html', users=users)

@app.route('/add_user', methods=['GET', 'POST'])
@login_required
def add_user():
    if request.method == 'POST':
        new_user = {
            'id': str(uuid.uuid4()),
            'username': request.form['username'],
            'password': request.form['password'],
            'expiry_date': request.form['expiry_date']
        }
        users = read_users()
        users.append(new_user)
        save_users(users)
        return redirect(url_for('index'))
    return render_template('add_user.html')

@app.route('/edit_user/<user_id>', methods=['GET', 'POST'])
@login_required
def edit_user(user_id):
    users = read_users()
    user = next((u for u in users if u['id'] == user_id), None)
    
    if request.method == 'POST':
        user.update({
            'username': request.form['username'],
            'password': request.form['password'],
            'expiry_date': request.form['expiry_date']
        })
        save_users(users)
        return redirect(url_for('index'))
    
    return render_template('edit_user.html', user=user)

@app.route('/delete_user/<user_id>', methods=['GET', 'POST'])
@login_required
def delete_user(user_id):
    users = read_users()
    users = [u for u in users if u['id'] != user_id]
    save_users(users)
    return redirect(url_for('index'))

# 新增注销路由
@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    return redirect(url_for('login'))

if __name__ == '__main__':
    init_csv()
    app.run(host='0.0.0.0', port=5000, debug=True)